/**
 * 图片优化工具类
 * 提供图片压缩、格式转换、懒加载等功能
 */

/**
 * 压缩图片
 * @param {File} file - 原始图片文件
 * @param {Object} options - 压缩选项
 * @returns {Promise<Blob>} 压缩后的图片
 */
export function compressImage(file, options = {}) {
  const {
    quality = 0.8,
    maxWidth = 1920,
    maxHeight = 1080,
    format = 'image/jpeg'
  } = options

  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()

    img.onload = () => {
      // 计算压缩后的尺寸
      let { width, height } = img
      
      if (width > maxWidth) {
        height = (height * maxWidth) / width
        width = maxWidth
      }
      
      if (height > maxHeight) {
        width = (width * maxHeight) / height
        height = maxHeight
      }

      canvas.width = width
      canvas.height = height

      // 绘制并压缩图片
      ctx.drawImage(img, 0, 0, width, height)
      
      canvas.toBlob(resolve, format, quality)
    }

    img.onerror = reject
    img.src = URL.createObjectURL(file)
  })
}

/**
 * 检查浏览器是否支持WebP格式
 * @returns {Promise<boolean>}
 */
export function supportsWebP() {
  return new Promise((resolve) => {
    const webP = new Image()
    webP.onload = webP.onerror = () => {
      resolve(webP.height === 2)
    }
    webP.src = ''
  })
}

/**
 * 获取优化后的图片URL
 * @param {string} originalUrl - 原始图片URL
 * @param {Object} options - 优化选项
 * @returns {string} 优化后的图片URL
 */
export function getOptimizedImageUrl(originalUrl, options = {}) {
  const {
    width,
    height,
    quality = 80,
    format = 'auto'
  } = options

  // 如果是本地图片，直接返回
  if (originalUrl.startsWith('/') || originalUrl.startsWith('./')) {
    return originalUrl
  }

  // 这里可以集成CDN服务，如阿里云OSS、腾讯云COS等
  // 示例：使用阿里云OSS的图片处理参数
  const params = []
  
  if (width) params.push(`w_${width}`)
  if (height) params.push(`h_${height}`)
  if (quality) params.push(`q_${quality}`)
  if (format !== 'auto') params.push(`f_${format}`)

  if (params.length > 0) {
    const separator = originalUrl.includes('?') ? '&' : '?'
    return `${originalUrl}${separator}x-oss-process=image/resize,${params.join(',')}`
  }

  return originalUrl
}

/**
 * 图片懒加载观察器
 */
class ImageLazyLoader {
  constructor(options = {}) {
    this.options = {
      rootMargin: '50px',
      threshold: 0.1,
      ...options
    }
    
    this.observer = new IntersectionObserver(
      this.handleIntersection.bind(this),
      this.options
    )
  }

  handleIntersection(entries) {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target
        const src = img.dataset.src
        
        if (src) {
          img.src = src
          img.removeAttribute('data-src')
          img.classList.add('loaded')
          this.observer.unobserve(img)
        }
      }
    })
  }

  observe(img) {
    this.observer.observe(img)
  }

  unobserve(img) {
    this.observer.unobserve(img)
  }

  disconnect() {
    this.observer.disconnect()
  }
}

// 创建全局懒加载实例
export const lazyLoader = new ImageLazyLoader()

/**
 * 预加载图片
 * @param {string|string[]} urls - 图片URL或URL数组
 * @returns {Promise<void>}
 */
export function preloadImages(urls) {
  const urlArray = Array.isArray(urls) ? urls : [urls]
  
  const promises = urlArray.map(url => {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.onload = resolve
      img.onerror = reject
      img.src = url
    })
  })

  return Promise.all(promises)
}

/**
 * 图片缓存管理
 */
class ImageCache {
  constructor(maxSize = 50) {
    this.cache = new Map()
    this.maxSize = maxSize
  }

  set(key, value) {
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value
      this.cache.delete(firstKey)
    }
    this.cache.set(key, value)
  }

  get(key) {
    return this.cache.get(key)
  }

  has(key) {
    return this.cache.has(key)
  }

  clear() {
    this.cache.clear()
  }
}

export const imageCache = new ImageCache()